package com.plusjun.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plusjun.common.constant.WareConstant;
import com.plusjun.common.utils.PageUtils;
import com.plusjun.common.utils.Query;
import com.plusjun.gulimall.ware.dao.PurchaseDao;
import com.plusjun.gulimall.ware.entity.PurchaseDetailEntity;
import com.plusjun.gulimall.ware.entity.PurchaseEntity;
import com.plusjun.gulimall.ware.service.PurchaseDetailService;
import com.plusjun.gulimall.ware.service.PurchaseService;
import com.plusjun.gulimall.ware.service.WareSkuService;
import com.plusjun.gulimall.ware.vo.MergeVO;
import com.plusjun.gulimall.ware.vo.PurchaseDoneVO;
import com.plusjun.gulimall.ware.vo.PurchaseItemDoneVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Resource
    private PurchaseDetailService purchaseDetailService;
    @Resource
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("purchase_id",key).or().eq("sku_id",key);
            });
        }
        String status = (String) params.get("status");
        if(StringUtils.isNotEmpty(status)) {
            wrapper.eq("status",status);
        }
        String wareId = (String) params.get("wareId");
        if(StringUtils.isNotEmpty(wareId)) {
            wrapper.eq("ware_id",wareId);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        if(purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setId(purchaseId);
            this.baseMapper.insert(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // 合并正确状态的采购单
        List<Long> items = mergeVO.getItems();
        List<Long> collect = items.stream().map(i -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            purchaseDetailService.listByIds(items);
            return detailEntity;
        }).filter(item -> {
            Integer status = item.getStatus();
            return (status == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                    status == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())
                    ? false : true;
        }).map(i -> {
            return i.getId();
        }).collect(Collectors.toList());
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = collect.stream().map(i -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntities);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        this.baseMapper.updateById(purchaseEntity);
    }

    @Transactional
    @Override
    public void received(List<Long> ids) {
        // 1、确认当前采购单是新建或者已分配采购单
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {

            Integer status = item.getStatus();
            return (status == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                    status == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())
                    ? true : false;
        }).map(item -> {
            int status = WareConstant.PurchaseDetailStatusEnum.BUYING.getCode();
            item.setStatus(status);
            return item;
        }).collect(Collectors.toList());
        // 2、改变采购的状态
        this.updateBatchById(collect);

        // 3、改变采购项状态
        collect.forEach(item -> {
           List<PurchaseDetailEntity> entities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(item1 -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                Long id = item1.getId();
                entity.setId(id);
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(entities);
        });
    }

    @Override
    public void done(PurchaseDoneVO vo) {
        Long id = vo.getId();
        // 2、该表采购项的状态
        Boolean flag = true;
        List<PurchaseItemDoneVO> items = vo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVO item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {
                detailEntity.setStatus(item.getStatus());
                // 3、将成功采购的入库
                Long itemId = item.getItemId();
                PurchaseDetailEntity entity = purchaseDetailService.getById(itemId);
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(updates);
        // 1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseDetailStatusEnum.FINISH.getCode():WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());

        // 3、将成功采购的入库

    }


}